class LayaMeScript {
    constructor() {

    }

    fileChange(type, _path1, _path2, _exportType) {
        const layaUIFolder = "pageUI" + codeMain.path.sep;
        const srcUIFolder = "uiScript";
        if (!window.proInfoObj || !window.proInfoObj.layaProType || window.proInfoObj.layaProType !== 100) {
            return;
        }
        if (!(_path1.endsWith(".scene") ||
            (type === "delete" && !_path1.endsWith(".ts") && !_path1.endsWith(".js")) )) {
            return;
        }
        let extname = codeMain.layameIns.extname = window.proInfoObj.proType === 1 ? ".ts" : ".js";
        let layaPagesFolder = path.join(codeMain.getWorkspaceRootPath(), "laya", "pages");
        let scenePath = path.relative(layaPagesFolder, _path1);
        if (!scenePath.startsWith(layaUIFolder)) {
            ERR(`${_path1}: 场景文件不在${layaUIFolder}下，将不进行操作!`);
            return;
        }
        let scriptRelativePath = scenePath.replace(".scene", extname);
        scriptRelativePath = scriptRelativePath.replace(layaUIFolder, srcUIFolder + codeMain.path.sep);
        let uiscriptPath = path.join(codeMain.getWorkspaceRootPath(), "src", scriptRelativePath);
        if (type === "create") {
            // _path1=F:/workspace/laya/layaair2_202102/layaair_layame_ts_026/laya/pages/pageUI/F.scene
            codeMain.layameIns.createFile(uiscriptPath, scriptRelativePath, _exportType);
        } else if (type === "delete") {
            // _path1=F:\workspace\laya\layaair2_202102\layaair_layame_ts_026\laya\pages\pageUI\F.scene
            codeMain.layameIns.deleteFile(uiscriptPath);
        } else if (type === "rename") {
            // _path1=F:\workspace\laya\layaair2_202102\layaair_layame_ts_026\laya\pages\pageUI\A.scene
            // _path2=A1
            let newPath = path.join(path.dirname(uiscriptPath), `${_path2}${extname}`)
            codeMain.layameIns.renameFile(uiscriptPath, newPath);
        } else if (type === "movefile") {
            // _path1=F:\workspace\laya\layaair2_202102\layaair_layame_ts_027\laya\pages\pageUI\A.scene
            // _path2=F:/workspace/laya/layaair2_202102/layaair_layame_ts_027/laya/pages/pageUI/a/A.scene
            let scene2Path = path.relative(layaPagesFolder, _path2);
            if (!scene2Path.startsWith(layaUIFolder)) {
                ERR(`${_path2}: 移动后位置不在${layaUIFolder}下，将不进行操作!`);
                return;
            }
            let script2RelativePath = scene2Path.replace(".scene", extname);
            script2RelativePath = script2RelativePath.replace(layaUIFolder, srcUIFolder + codeMain.path.sep);
            let ui2scriptPath = path.join(codeMain.getWorkspaceRootPath(), "src", script2RelativePath);
            codeMain.layameIns.moveFile(uiscriptPath, ui2scriptPath);
        } else if (type === "clone") {
            // _path1=F:\workspace\laya\layaair2_202102\layaair_layame_ts_027\laya\pages\pageUI\a\A.scene
            // _path2=F:\workspace\laya\layaair2_202102\layaair_layame_ts_027\laya\pages\pageUI\a\A1.scene
            let scene2Path = path.relative(layaPagesFolder, _path2);
            if (!scene2Path.startsWith(layaUIFolder)) {
                ERR(`${_path2}: clone后位置不在${layaUIFolder}下，将不进行操作!`);
                return;
            }
            let script2RelativePath = scene2Path.replace(".scene", extname);
            script2RelativePath = script2RelativePath.replace(layaUIFolder, srcUIFolder + codeMain.path.sep);
            let ui2scriptPath = path.join(codeMain.getWorkspaceRootPath(), "src", script2RelativePath);
            codeMain.layameIns.createFile(ui2scriptPath);
        }
    }

    createFile(filePath, scriptRelativePath, _exportType) {
        if (codeMain.fs.existsSync(filePath)) {
            ERR(`${filePath} 文件已存在，不再进行创建操作!`);
            return false;
        }
        let folderPath = path.dirname(filePath);
        let relativePath = path.relative(codeMain.getWorkspaceRootPath(), folderPath);
        let folderList = relativePath.split(path.sep);
        folderPath = codeMain.getWorkspaceRootPath();
        for (let i = 0, len = folderList.length; i < len; i++) {
            folderPath = path.join(folderPath, folderList[i]);
            if (codeMain.fs.existsSync(folderPath)) {
                continue;
            }
            codeMain.fs.mkdirSync(folderPath);
        }
         
        let data = fs.readFileSync(path.join(__dirname, "tpl", `uiscript${codeMain.layameIns.extname}`), "utf8");
        let fileName = path.basename(filePath, codeMain.layameIns.extname);
        if (fileName && !fileName.includes(".")) {
            data = data.replace(/uiscript/mg, fileName);
            // 如果使用了分离模式
            if(_exportType == '分离模式' || _exportType == 'Split') { 
            
                // 改成这样的格式
                // import { ui } from "../ui/layaMaxUI"; 
                // export default class qqq extends ui.pageUI.qqqUI {
                let pathArr = [];
                if (scriptRelativePath.includes('\\')) {
                    pathArr = scriptRelativePath.split('\\');
                } else { 
                    pathArr = scriptRelativePath.split('/');
                }
                let importUiStr = '../ui/layaMaxUI';
                let superClsStr = 'ui.pageUI.';
                let codeFileName = pathArr[pathArr.length -1];
                let isJs = false;
                for( let i = 0 ,len = pathArr.length; i < len; i ++) {
                    if (i >= 2) {
                        importUiStr = '../' + importUiStr; 
                    }
                    if (i> 0 && i < len - 1) {
                        superClsStr = superClsStr + pathArr[i] + '.';
                    }
                } 
                if (codeFileName.lastIndexOf('.js') > 0) {
                    isJs = true;
                    superClsStr = fileName + 'UI';
                } else { 
                    superClsStr = superClsStr + fileName + 'UI';
                }
                data = data.replace(/class/mg, 'export default class');
                data = data.replace(/ScriptView/mg, superClsStr);
                if (isJs) { 
                    data = `import { ${superClsStr} } from "${importUiStr}";\n` + data;    
                } else { 
                    data = `import { ui } from "${importUiStr}";\n` + data;    
                }
            }
        }
        codeMain.fs.writeFileSync(filePath, data, "utf8");
        return true;
    }

    deleteFile(filePath) {
        if (!codeMain.fs.existsSync(filePath)) {
            ERR(`${filePath} 文件不存在，无法进行删除操作!`);
            return false;
        }
        if (codeMain.fs.statSync(filePath).isDirectory()) {
            codeMain.layameIns.removeDirectory(filePath);
        } else {
            codeMain.fs.unlinkSync(filePath);
        }
        return true;
    }

    removeDirectory(folderPath) {
        let files = codeMain.fs.readdirSync(folderPath);
        let fileName, filePath;
        for (let i = 0, len = files.length; i < len; i++) {
            fileName = files[i];
            filePath = codeMain.path.join(folderPath, fileName);
            if (codeMain.fs.statSync(filePath).isDirectory()) {
                codeMain.layameIns.removeDirectory(filePath);
            } else {
                codeMain.fs.unlinkSync(filePath);
            }
        }
        try {
            codeMain.fs.rmdirSync(folderPath);
        } catch(e) {
            console.error("删除文件夹失败", e);
        }
        return true;
    }

    renameFile(oldPath, newPath) {
        if (!codeMain.fs.existsSync(oldPath)) {
            ERR(`${oldPath} 文件不存在，无法进行重命名操作!`);
            return false;
        }
        if (codeMain.fs.existsSync(newPath)) {
            ERR(`${newPath} 文件已存在，不再进行重命名操作`);
            return false;
        }
        codeMain.fs.renameSync(oldPath, newPath);
        return true;
    }

    moveFile(oldPath, newPath) {
        if (!codeMain.fs.existsSync(oldPath)) {
            ERR(`${oldPath} 文件不存在，无法进行移动操作!`);
            return false;
        }
        if (codeMain.fs.existsSync(newPath)) {
            ERR(`${newPath} 文件已存在，无法进行移动操作`);
            return false;
        }
        codeMain.layameIns.createFile(newPath); // 保证路径文件夹创建
        let con = codeMain.fs.readFileSync(oldPath, "utf8");
        fs.writeFileSync(newPath, con, "utf8");
        fs.unlinkSync(oldPath);
        return true;
    }
}

function Log(...params) {
    if (params instanceof Array) {
        console.log(...params);
    } else 
        console.log(params);
}

function ERR(...params) {
    if (params instanceof Array) {
        console.error("layame script: ", ...params);
    } else 
        console.error("layame script: ", params);
}

module.exports = LayaMeScript;